/**
 * 小组件
 */
app.factory('utils', ['$http', 'gConfig', function($http, gConfig) {
  return {
    // 格式化post数据
    transformRequestAsFormPost: function() {
      // I prepare the request data for the form post.
      function transformRequest(data, getHeaders) {
        var headers = getHeaders();
        headers["Content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
        return (serializeData(data));
      }
      // Return the factory value.
      return (transformRequest);

      function serializeData(data) {
        // If this is not an object, defer to native stringification.
        if (!angular.isObject(data)) {
          return ((data == null) ? "" : data.toString());
        }

        var buffer = [];
        // Serialize each key in the object.
        for (var name in data) {
          if (!data.hasOwnProperty(name)) {
            continue;
          }
          var value = data[name];
          buffer.push(
            encodeURIComponent(name) +
            "=" +
            encodeURIComponent((value == null) ? "" : value)
          );
        }
        // Serialize the buffer and clean it up for transportation.
        var source = buffer
          .join("&")
          .replace(/%20/g, "+");
        return (source);
      }
    },
    // 获取数据
    get: function(apiname, params) {
      return $http.get(gConfig.api[apiname], {
        params: params
      });
    },

    // 提交数据
    post: function(apiname, params) {
      return $http.post(gConfig.api[apiname], params, {
        transformRequest: this.transformRequestAsFormPost,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
    },

    // 格式化时间
    formatDate: function(date, fmt) {
      var date = new Date(date) 
      function pad(value) {
        return (value.toString().length < 2) ? '0' + value : value;
      }
      return fmt.replace(/%([a-zA-Z])/g, function(_, fmtCode) {
        switch (fmtCode) {
          case 'Y':
            return date.getFullYear();
          case 'M':
            return pad(date.getMonth() + 1);
          case 'd':
            return pad(date.getDate());
          case 'H':
            return pad(date.getHours());
          case 'm':
            return pad(date.getMinutes());
          case 's':
            return pad(date.getSeconds());
          default:
            throw new Error('Unsupported format code: ' + fmtCode);
        }
      });
    }


  };
}]);
